// Dashboard页面功能
document.addEventListener('DOMContentLoaded', function() {
    console.log('=== Dashboard页面加载 ===');
    
    const API_BASE_URL = 'http://localhost:8080/userapi';
    const USER_API_BASE_URL = 'http://localhost:8080/api';
    let currentUser = null;

    // 工具函数
    const utils = {
        // 获取token
        getToken() {
            return 'mock-token-for-testing';
        },

        // 获取当前用户ID
        async getCurrentUserId() {
            const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
            
            // 如果有存储的用户信息，直接使用userId
            if (user.userId) {
                console.log('使用存储的用户ID:', user.userId);
                console.log('当前用户信息:', user);
                return user.userId;
            }
            
            // 如果没有用户信息，尝试根据手机号查找用户
            const phone = user.phone;
            if (phone) {
                console.log('根据手机号查找用户:', phone);
                try {
                    const response = await fetch(`${USER_API_BASE_URL}/users/phone/${phone}`, {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        const userId = data.data.userId;
                        console.log('通过API找到用户ID:', userId);
                        
                        // 更新存储的用户信息
                        const updatedUser = { ...user, userId: userId };
                        if (localStorage.getItem('user')) {
                            localStorage.setItem('user', JSON.stringify(updatedUser));
                        } else if (sessionStorage.getItem('user')) {
                            sessionStorage.setItem('user', JSON.stringify(updatedUser));
                        }
                        
                        return userId;
                    } else {
                        console.log('手机号对应的用户不存在:', phone);
                        // 如果手机号不存在，使用默认用户ID
                        return 'U000000001';
                    }
                } catch (error) {
                    console.error('根据手机号获取用户ID失败:', error);
                    // 网络错误时使用默认用户ID
                    return 'U000000001';
                }
            }
            
            // 如果都没有，使用默认值
            console.log('使用默认用户ID: U000000001');
            return 'U000000001';
        },

        // 显示加载状态
        showLoading() {
            const loading = document.getElementById('loading');
            if (loading) loading.style.display = 'flex';
        },

        // 隐藏加载状态
        hideLoading() {
            const loading = document.getElementById('loading');
            if (loading) loading.style.display = 'none';
        },

        // 显示消息
        showMessage(message, isError = false) {
            const messageDiv = document.getElementById('message');
            if (messageDiv) {
                messageDiv.textContent = message;
                messageDiv.className = isError ? 'message error' : 'message success';
                messageDiv.style.display = 'block';
                setTimeout(() => {
                    messageDiv.style.display = 'none';
                }, 3000);
            }
        },

        // 处理响应
        async handleResponse(response) {
            console.log('响应状态:', response.status);
            console.log('响应头:', response.headers);
            
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                const data = await response.json();
                console.log('响应内容:', data);
                
                if (!response.ok) {
                    console.log('错误响应内容:', data);
                    throw new Error(data.message || '请求失败');
                }
                return data;
            } else {
                const text = await response.text();
                console.log('响应内容:', text);
                
                if (!response.ok) {
                    throw new Error('请求失败');
                }
                return text;
            }
        }
    };

    // 用户管理
    const userManager = {
        // 获取用户信息
        async fetchUserProfile() {
            try {
                utils.showLoading();
                console.log('开始获取用户信息...');
                
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}`, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                console.log('获取用户信息响应:', response);
                const data = await utils.handleResponse(response);
                
                // 处理user模块的响应格式
                if (data.user && data.privacy) {
                    // 合并用户信息和隐私设置
                    currentUser = { ...data.user, ...data.privacy };
                } else {
                    currentUser = data;
                }
                
                this.updateUI(currentUser);
                this.populateForm(currentUser);
                
            } catch (error) {
                console.error('获取用户信息失败:', error);
                utils.showMessage(error.message, true);
            } finally {
                utils.hideLoading();
            }
        },

        // 更新用户信息
        async updateProfile(formData) {
            try {
                utils.showLoading();
                console.log('开始更新用户信息...');
                console.log('更新数据:', formData);
                
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                console.log('更新用户信息响应:', response);
                const data = await utils.handleResponse(response);
                
                // 更新当前用户数据
                currentUser = { ...currentUser, ...data };
                
                // 更新UI显示
                this.updateUI(currentUser);
                
                // 重新填充表单
                this.populateForm(currentUser);
                
                utils.showMessage('用户信息更新成功');
                return true;
            } catch (error) {
                console.error('更新用户信息失败:', error);
                utils.showMessage(error.message, true);
                return false;
            } finally {
                utils.hideLoading();
            }
        },

        // 更新UI
        updateUI(data) {
            console.log('更新UI显示:', data);
            
            // 更新用户基本信息
            const nicknameElements = document.querySelectorAll('.profile-info h3, .user-info h4');
            nicknameElements.forEach(el => {
                el.textContent = data.nickname || '用户名';
            });

            const uidElements = document.querySelectorAll('.user-id, .user-info p');
            uidElements.forEach(el => {
                el.textContent = `UID: ${data.gameUid || '未绑定'}`;
            });

            // 更新头像
            const avatarElements = document.querySelectorAll('.profile-avatar img, .user-avatar img');
            avatarElements.forEach(img => {
                img.src = data.avatar || 'images/default-avatar.png';
            });

            // 更新等级信息
            const levelElements = document.querySelectorAll('.level-number, .level-number-large');
            levelElements.forEach(el => {
                el.textContent = data.level || 1;
            });

            const levelNameElements = document.querySelectorAll('.level-name, .level-name-large');
            levelNameElements.forEach(el => {
                el.textContent = this.getLevelName(data.level || 1);
            });

            // 更新经验值
            const expElements = document.querySelectorAll('.current-exp');
            expElements.forEach(el => {
                el.textContent = data.experience || 0;
            });

            const nextLevelExpElements = document.querySelectorAll('.next-level-exp');
            nextLevelExpElements.forEach(el => {
                el.textContent = this.getNextLevelExp(data.level || 1);
            });

            const expProgressElements = document.querySelectorAll('.exp-progress, .exp-progress-large');
            expProgressElements.forEach(el => {
                const progress = this.calculateExpProgress(data.experience || 0, data.level || 1);
                el.style.width = `${progress}%`;
            });

            const expTextElements = document.querySelectorAll('.exp-text');
            expTextElements.forEach(el => {
                el.textContent = `${data.experience || 0}/${this.getNextLevelExp(data.level || 1)} 经验`;
            });

            const expToNextElements = document.querySelectorAll('.exp-to-next');
            expToNextElements.forEach(el => {
                const needed = this.getNextLevelExp(data.level || 1) - (data.experience || 0);
                el.textContent = `距离下一级还需 ${needed} 经验`;
            });

            // 更新游戏账号显示
            this.updateAccountDisplay(data.gameUid);
        },

        // 填充表单
        populateForm(data) {
            const form = document.getElementById('editProfileForm');
            if (!form) {
                console.error('找不到编辑资料表单');
                return;
            }

            console.log('填充表单数据:', data);

            // 填充基本信息
            const nicknameInput = form.querySelector('#nickname');
            if (nicknameInput) {
                nicknameInput.value = data.nickname || '';
                console.log('设置昵称:', data.nickname);
            }

            const emailInput = form.querySelector('#email');
            if (emailInput) {
                emailInput.value = data.email || '';
                console.log('设置邮箱:', data.email);
            }

            const genderSelect = form.querySelector('#gender');
            if (genderSelect) {
                genderSelect.value = data.gender ? data.gender.toString() : '';
                console.log('设置性别:', data.gender);
            }

            const gameUidInput = form.querySelector('#gameUid');
            if (gameUidInput) {
                gameUidInput.value = data.gameUid || '';
                console.log('设置游戏UID:', data.gameUid);
            }

            // 设置头像选择
            const selectedAvatarInput = form.querySelector('#selectedAvatar');
            if (selectedAvatarInput && data.avatar) {
                selectedAvatarInput.value = data.avatar;
                console.log('设置头像:', data.avatar);
                
                // 更新头像选择的视觉状态
                const avatarOptions = document.querySelectorAll('.avatar-option');
                avatarOptions.forEach(option => {
                    const avatarPath = option.getAttribute('data-avatar');
                    if (avatarPath === data.avatar) {
                        option.classList.add('selected');
                        console.log('选中头像选项:', avatarPath);
                    } else {
                        option.classList.remove('selected');
                    }
                });
            }
        },

        // 更新游戏账号显示
        updateAccountDisplay(gameUid) {
            console.log('更新游戏账号显示，gameUid:', gameUid, '类型:', typeof gameUid);
            
            const accountInfo = document.getElementById('accountInfo');
            const emptyAccountState = document.getElementById('emptyAccountState');
            const gameUidDisplay = document.getElementById('gameUidDisplay');
            const bindAccountBtns = document.querySelectorAll('.bind-account-btn');

            if (gameUid && gameUid.trim() !== '') {
                // 显示已绑定的账号信息
                console.log('显示已绑定状态');
                accountInfo.style.display = 'block';
                emptyAccountState.style.display = 'none';
                gameUidDisplay.textContent = gameUid;
                
                // 禁用绑定按钮
                bindAccountBtns.forEach(btn => {
                    btn.disabled = true;
                    btn.innerHTML = '<i class="fas fa-check"></i> 已绑定';
                    btn.style.background = '#28a745';
                    btn.style.cursor = 'not-allowed';
                });
            } else {
                // 显示未绑定状态
                console.log('显示未绑定状态');
                accountInfo.style.display = 'none';
                emptyAccountState.style.display = 'block';
                gameUidDisplay.textContent = '未绑定';
                
                // 启用绑定按钮
                bindAccountBtns.forEach(btn => {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-plus"></i> 绑定账号';
                    btn.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
                    btn.style.cursor = 'pointer';
                });
            }
        },

        // 解绑游戏账号
        async unbindGameAccount() {
            try {
                utils.showLoading();
                console.log('开始解绑游戏UID...');

                const userId = await utils.getCurrentUserId();
                
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}/unbind-uid`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                console.log('解绑游戏UID响应:', response);
                const data = await utils.handleResponse(response);

                utils.showMessage('游戏UID解绑成功');
                
                // 重新获取用户信息以更新显示
                await userManager.fetchUserProfile();

            } catch (error) {
                console.error('解绑游戏UID失败:', error);
                utils.showMessage(error.message, true);
            } finally {
                utils.hideLoading();
            }
        },

        // 获取等级名称
        getLevelName(level) {
            const levelNames = {
                1: '新手',
                2: '学徒',
                3: '熟练者',
                4: '专家',
                5: '大师',
                6: '传奇',
                7: '神话',
                8: '传说',
                9: '至尊',
                10: '王者'
            };
            return levelNames[level] || '新手';
        },

        // 获取下一级所需经验
        getNextLevelExp(level) {
            return level * 100; // 简单的经验计算规则
        },

        // 计算经验进度百分比
        calculateExpProgress(experience, level) {
            const nextLevelExp = this.getNextLevelExp(level);
            return Math.min((experience / nextLevelExp) * 100, 100);
        }
    };

    // 表单管理
    const formManager = {
        // 初始化编辑资料表单
        initEditProfileForm() {
            const form = document.getElementById('editProfileForm');
            if (!form) {
                console.error('找不到编辑资料表单');
                return;
            }

            // 初始化头像选择
            this.initAvatarSelection();

            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                console.log('表单提交事件触发');
                
                // 获取表单数据
                const nickname = form.querySelector('#nickname');
                const email = form.querySelector('#email');
                const gender = form.querySelector('#gender');
                const gameUid = form.querySelector('#gameUid');
                const selectedAvatar = form.querySelector('#selectedAvatar');
                
                console.log('表单字段:', {
                    nickname: nickname?.value,
                    email: email?.value,
                    gender: gender?.value,
                    gameUid: gameUid?.value,
                    avatar: selectedAvatar?.value
                });
                
                // 构建表单数据，过滤空值
                const formData = {};
                
                if (nickname?.value?.trim()) {
                    formData.nickname = nickname.value.trim();
                }
                
                if (email?.value?.trim()) {
                    formData.email = email.value.trim();
                }
                
                if (gender?.value) {
                    formData.gender = parseInt(gender.value);
                }
                
                if (gameUid?.value?.trim()) {
                    formData.gameUid = gameUid.value.trim();
                }
                
                if (selectedAvatar?.value?.trim()) {
                    formData.avatar = selectedAvatar.value.trim();
                }

                console.log('准备提交的数据:', formData);

                const success = await userManager.updateProfile(formData);
                if (success) {
                    // 关闭模态窗口
                    const modal = document.getElementById('editProfileModal');
                    if (modal) {
                        modal.style.display = 'none';
                    }
                }
            });
        },

        // 初始化头像选择
        initAvatarSelection() {
            const avatarOptions = document.querySelectorAll('.avatar-option');
            const selectedAvatarInput = document.getElementById('selectedAvatar');

            avatarOptions.forEach(option => {
                option.addEventListener('click', () => {
                    // 移除其他选项的选中状态
                    avatarOptions.forEach(opt => opt.classList.remove('selected'));
                    
                    // 添加当前选项的选中状态
                    option.classList.add('selected');
                    
                    // 更新隐藏输入框的值
                    const avatarPath = option.getAttribute('data-avatar');
                    selectedAvatarInput.value = avatarPath;
                    
                    console.log('选择的头像:', avatarPath);
                });
            });
        },

        // 初始化修改密码表单
        initChangePasswordForm() {
            const form = document.getElementById('changePasswordForm');
            if (!form) {
                console.error('找不到修改密码表单');
                return;
            }

            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                console.log('修改密码表单提交事件触发');
                
                await this.submitChangePassword();
            });

            // 初始化密码显示切换
            this.initPasswordToggles();
        },

        // 初始化密码显示切换
        initPasswordToggles() {
            const toggleButtons = document.querySelectorAll('.toggle-password');
            toggleButtons.forEach(button => {
                button.addEventListener('click', () => {
                    const input = button.previousElementSibling;
                    if (input.type === 'password') {
                        input.type = 'text';
                        button.classList.remove('fa-eye-slash');
                        button.classList.add('fa-eye');
                    } else {
                        input.type = 'password';
                        button.classList.remove('fa-eye');
                        button.classList.add('fa-eye-slash');
                    }
                });
            });
        },

        // 提交修改密码请求
        async submitChangePassword() {
            const submitBtn = document.querySelector('#changePasswordForm button[type="submit"]');
            const form = document.getElementById('changePasswordForm');
            
            if (!form) {
                console.error('找不到修改密码表单');
                return;
            }

            // 获取表单数据
            const oldPassword = form.querySelector('#oldPassword').value;
            const newPassword = form.querySelector('#newPassword').value;
            const confirmNewPassword = form.querySelector('#confirmNewPassword').value;

            // 验证表单
            if (!oldPassword || !newPassword || !confirmNewPassword) {
                utils.showMessage('请填写所有密码字段', true);
                return;
            }

            if (newPassword !== confirmNewPassword) {
                utils.showMessage('新密码与确认密码不匹配', true);
                return;
            }

            if (newPassword.length < 6) {
                utils.showMessage('新密码长度至少6位', true);
                return;
            }

            // 显示加载状态
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 修改中...';
            submitBtn.disabled = true;

            try {
                utils.showLoading();
                console.log('开始修改密码...');

                const userId = await utils.getCurrentUserId();
                
                // 构建URL参数
                const params = new URLSearchParams({
                    oldPassword: oldPassword,
                    newPassword: newPassword
                });
                
                const response = await fetch(`${USER_API_BASE_URL}/users/${userId}/password?${params}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                console.log('修改密码响应:', response);
                const data = await utils.handleResponse(response);

                utils.showMessage('密码修改成功');
                
                // 清空表单
                form.reset();
                
                // 关闭模态窗口
                const modal = document.getElementById('changePasswordModal');
                if (modal) {
                    modal.style.display = 'none';
                }

            } catch (error) {
                console.error('修改密码失败:', error);
                utils.showMessage(error.message, true);
            } finally {
                utils.hideLoading();
                submitBtn.innerHTML = '<i class="fas fa-key"></i> 修改密码';
                submitBtn.disabled = false;
            }
        },

        // 初始化绑定游戏账号表单
        initBindGameAccountForm() {
            const form = document.getElementById('bindGameAccountForm');
            if (!form) {
                console.error('找不到绑定游戏账号表单');
                return;
            }

            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                console.log('绑定游戏账号表单提交事件触发');
                
                await this.submitBindGameAccount();
            });
        },

        // 提交绑定游戏账号请求
        async submitBindGameAccount() {
            const submitBtn = document.querySelector('#bindGameAccountForm button[type="submit"]');
            const form = document.getElementById('bindGameAccountForm');
            
            if (!form) {
                console.error('找不到绑定游戏账号表单');
                return;
            }

            // 获取表单数据
            const gameUid = form.querySelector('#gameUid').value.trim();

            // 验证表单
            if (!gameUid) {
                utils.showMessage('请输入游戏UID', true);
                return;
            }

            // 验证UID格式：8位数字
            if (!/^\d{8}$/.test(gameUid)) {
                utils.showMessage('游戏UID格式不正确，请输入8位数字', true);
                return;
            }

            // 显示加载状态
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 绑定中...';
            submitBtn.disabled = true;

            try {
                utils.showLoading();
                console.log('开始绑定游戏UID...');

                const userId = await utils.getCurrentUserId();
                
                // 构建URL参数
                const params = new URLSearchParams({
                    gameUid: gameUid
                });
                
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}/bind-uid?${params}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                console.log('绑定游戏UID响应:', response);
                const data = await utils.handleResponse(response);

                utils.showMessage('游戏UID绑定成功');
                
                // 清空表单
                form.reset();
                
                // 关闭模态窗口
                const modal = document.getElementById('bindGameAccountModal');
                if (modal) {
                    modal.style.display = 'none';
                }

                // 重新获取用户信息以更新显示
                await userManager.fetchUserProfile();

            } catch (error) {
                console.error('绑定游戏UID失败:', error);
                utils.showMessage(error.message, true);
            } finally {
                utils.hideLoading();
                submitBtn.innerHTML = '绑定';
                submitBtn.disabled = false;
            }
        }
    };

    // 模态窗口管理
    const modalManager = {
        showModal(modal) {
            if (modal) {
                modal.style.display = 'flex';
            }
        },

        hideModal(modal) {
            if (modal) {
                modal.style.display = 'none';
            }
        }
    };

    // 初始化
    async function init() {
        console.log('初始化Dashboard...');
        
        // 获取用户信息
        await userManager.fetchUserProfile();
        
        // 初始化表单
        formManager.initEditProfileForm();
        formManager.initChangePasswordForm();
        formManager.initBindGameAccountForm();
        
        // 绑定事件
        bindEvents();
    }

    // 绑定事件
    function bindEvents() {
        // 编辑资料按钮
        const editProfileBtn = document.querySelector('.edit-profile-btn');
        if (editProfileBtn) {
            editProfileBtn.addEventListener('click', () => {
                const modal = document.getElementById('editProfileModal');
                modalManager.showModal(modal);
            });
        }

        // 修改密码菜单
        const changePasswordMenu = document.getElementById('changePasswordMenu');
        if (changePasswordMenu) {
            changePasswordMenu.addEventListener('click', (e) => {
                e.preventDefault();
                console.log('点击修改密码菜单');
                const modal = document.getElementById('changePasswordModal');
                modalManager.showModal(modal);
            });
        }

        // 绑定游戏账号按钮
        const bindAccountBtns = document.querySelectorAll('.bind-account-btn');
        bindAccountBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                
                // 检查按钮是否被禁用
                if (btn.disabled) {
                    console.log('绑定按钮已被禁用，无法点击');
                    return;
                }
                
                console.log('点击绑定游戏账号按钮');
                const modal = document.getElementById('bindGameAccountModal');
                modalManager.showModal(modal);
            });
        });

        // 解绑游戏账号按钮
        const unbindAccountBtn = document.getElementById('unbindAccountBtn');
        if (unbindAccountBtn) {
            unbindAccountBtn.addEventListener('click', async (e) => {
                e.preventDefault();
                console.log('点击解绑游戏账号按钮');
                
                if (confirm('确定要解绑游戏账号吗？此操作不可撤销。')) {
                    await userManager.unbindGameAccount();
                }
            });
        }

        // 关闭模态窗口
        const closeButtons = document.querySelectorAll('.close-modal');
        closeButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const modal = btn.closest('.modal');
                modalManager.hideModal(modal);
            });
        });

        // 点击模态窗口外部关闭
        const modals = document.querySelectorAll('.modal');
        modals.forEach(modal => {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modalManager.hideModal(modal);
                }
            });
        });
    }

    // 启动应用
    init();
}); 